package org.baicaixiaozhan.springbootwebdemo2.Dao;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.baicaixiaozhan.springbootwebdemo2.domain.User;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;

import java.util.List;

import static org.baicaixiaozhan.springbootwebdemo2.domain.UserPermissions.ROLE_ADMIN;
import static org.baicaixiaozhan.springbootwebdemo2.domain.UserPermissions.ROLE_STUDENT;

/**
 * DESC:
 *
 * @author : baicaixiaozhan
 * @since : 2021-02-06
 */
@Repository
public class UserDao {
    private static List<User> userList;

    {
        userList = Lists.newArrayList(
                User.builder().username("zhangsan").password("123456").authorities(ROLE_ADMIN.getGrantedAuthorities()).build(),
                User.builder().username("lisi").password("123456").authorities(ROLE_STUDENT.getGrantedAuthorities()).build()
        );
    }

    public User findUserByUsername(String username) {
        return userList.stream()
                .filter(user -> username.equals(user.getUsername()))
                .findFirst()
                .orElseThrow(() ->
                        new UsernameNotFoundException(Strings.lenientFormat("没有找到 username 为 %s 的用户", username))
                );
    }
}
